package com.sqly.doc.menu.camera;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;
import com.sqly.doc.R;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.util.Constants;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.PictureUtil;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.SweetAlertDialogUtil;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.ContentType;

public class CameraChoose extends MyBaseActivity {

    TextView title, uname;
    private Button btn_paizhao, btn_xiangce;
    private ImageView headIv;
    private TextView textView;
    private static final String TAG = "CameraChoose";
    private static final int REQUEST_PERMISSION_CODE = 101;
    private static final int REQUEST_IMAGE_GET = 0;
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int REQUEST_SMALL_IMAGE_CUTTING = 2;
    private static final int REQUEST_CHANGE_USER_NICK_NAME = 10;
    private static final String IMAGE_FILE_NAME = "upload_image_icon.jpg";
    Context con = CameraChoose.this;
    String picname = "";
    LinearLayout back;

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_camera_choose);
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("现场拍照");
        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        uname.setText("确定上传");
        btn_paizhao = findViewById(R.id.btn_paizhao);
        btn_xiangce = findViewById(R.id.btn_xiangce);
        textView = findViewById(R.id.tv);
        headIv = findViewById(R.id.iv);
        //showHeadImage();
        btn_paizhao.setOnClickListener(new Listener());
        btn_xiangce.setOnClickListener(new Listener());
        uname.setOnClickListener(new Listener());
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 回调成功
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 切割
                case REQUEST_SMALL_IMAGE_CUTTING:
                    Log.e(TAG,"before show");
                    File cropFile=new File(PictureUtil.getMyRootDirectory(),"crop.jpg");
                    Uri cropUri = Uri.fromFile(cropFile);
                    setPicToView(cropUri);
                    break;

                // 相册选取
                case REQUEST_IMAGE_GET:
                    Uri uri= PictureUtil.getImageUri(this, data);
                    startPhotoZoom(uri);
                    break;

                // 拍照
                case REQUEST_IMAGE_CAPTURE:
                    File pictureFile = new File(PictureUtil.getMyRootDirectory(), IMAGE_FILE_NAME);
                    Uri pictureUri;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        pictureUri = FileProvider.getUriForFile(this, "com.sqly.doc.fileprovider", pictureFile);
                        Log.e(TAG,"picURI="+pictureUri.toString());
                    } else {
                        pictureUri = Uri.fromFile(pictureFile);
                    }
                    Bitmap bmTemp= BitmapFactory.decodeFile(pictureFile.getPath());
                    int degree = PictureUtil.readPictureDegree(pictureFile.getPath());
                    Bitmap bmpOk = PictureUtil.rotateToDegrees(bmTemp, degree);
                    MediaStore.Images.Media.insertImage(getContentResolver(), bmpOk, "", "");
                    startPhotoZoom(pictureUri);
                    break;
                default:
            }
        }else{
            Log.e(TAG,"result = "+resultCode+",request = "+requestCode);
        }
    }

    class Listener implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_paizhao:
                    //创建存放头像的文件夹
                    PictureUtil.mkdirMyRootDirectory();
                    // 拍照及文件权限申请
                    if (ContextCompat.checkSelfPermission(CameraChoose.this,
                            Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                            || ContextCompat.checkSelfPermission(CameraChoose.this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        // 权限还没有授予，进行申请
                        ActivityCompat.requestPermissions(CameraChoose.this,
                                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 300); // 申请的 requestCode 为 300
                    } else {
                        // 权限已经申请，直接拍照
                        imageCapture();
                    }
                    break;

                case R.id.btn_xiangce:
                    //创建存放头像的文件夹
                    PictureUtil.mkdirMyRootDirectory();
                    // 文件权限申请
                    if (ContextCompat.checkSelfPermission(CameraChoose.this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        // 权限还没有授予，进行申请
                        ActivityCompat.requestPermissions(CameraChoose.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200); // 申请的 requestCode 为 200
                    } else {
                        // 如果权限已经申请过，直接进行图片选择
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        // 判断系统中是否有处理该 Intent 的 Activity
                        if (intent.resolveActivity(getPackageManager()) != null) {
                            startActivityForResult(intent, REQUEST_IMAGE_GET);
                        } else {
                            Toast.makeText(CameraChoose.this, "未找到图片查看器", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case R.id.uname:
                    //上传图片
                    uploadImg();
                    break;
            }
        }
    }

    //拍照
    private void imageCapture() {
        Intent intent;
        Uri pictureUri;
        //getMyRootDirectory()得到的是Environment.getExternalStorageDirectory() + File.separator+"MyPet"
        //也就是我之前创建的存放头像的文件夹（目录）
        File pictureFile = new File(PictureUtil.getMyRootDirectory(), IMAGE_FILE_NAME);
        // 判断当前系统
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //这一句非常重要
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //""中的内容是随意的，但最好用package名.provider名的形式，清晰明了
            pictureUri = FileProvider.getUriForFile(this, "com.sqly.doc.fileprovider", pictureFile);
        } else {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            pictureUri = Uri.fromFile(pictureFile);
        }
        // 去拍照,拍照的结果存到pictureUri对应的路径中
        intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
        Log.e(TAG,"before take photo"+pictureUri.toString());
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }

    //以下为头像相关方法
    private void showHeadImage() {
        boolean isSdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);// 判断sdcard是否存在
        if (isSdCardExist) {
            String path = (String) SharedPreferencesUtils.getParam(this, Constants.UPLOAD_IMAGE, "");// 获取图片路径

            File file = new File(path);
            if (file.exists()) {
                Bitmap bm = BitmapFactory.decodeFile(path);
                //MediaStore.Images.Media.insertImage(getContentResolver(), bm, "", "");
                // 将图片显示到ImageView中
                headIv.setImageBitmap(bm);
            }else{
                Log.e(TAG,"no file");
                headIv.setImageResource(R.mipmap.renxiang);
            }
        } else {
            Log.e(TAG,"no SD card");
            headIv.setImageResource(R.mipmap.renxiang);
        }

    }

    /**
     * 截图后保存图片
     * @param uri
     */
    public void setPicToView(Uri uri)  {
        if (uri != null) {
            Bitmap photo = null;
            try {
                photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
            }catch (FileNotFoundException e){
                e.printStackTrace();
            }
            // 创建 smallIcon 文件夹
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //String storage = Environment.getExternalStorageDirectory().getPath();
                File dirFile = new File(PictureUtil.getMyRootDirectory(),  "Icon");
                if (!dirFile.exists()) {
                    if (!dirFile.mkdirs()) {
                        Log.d(TAG, "in setPicToView->文件夹创建失败");
                    } else {
                        Log.d(TAG, "in setPicToView->文件夹创建成功");
                    }
                }
                File file = new File(dirFile, IMAGE_FILE_NAME);
                SharedPreferencesUtils.setParam(this, Constants.UPLOAD_IMAGE, file.getPath());
                // 保存图片
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(file);
                    photo.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    outputStream.flush();
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 在视图中显示图片
            showHeadImage();
            //circleImageView_user_head.setImageBitmap( SharedPreferencesUtils.getParam(Constants.UserInfo.GEAD_IMAGE));
        }
    }
    private void startPhotoZoom(Uri uri) {
        Log.d(TAG,"Uri = "+uri.toString());
        //保存裁剪后的图片
        File cropFile=new File(PictureUtil.getMyRootDirectory(),"crop.jpg");
        try{
            if(cropFile.exists()){
                cropFile.delete();
                Log.e(TAG,"delete");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        Uri cropUri;
        cropUri = Uri.fromFile(cropFile);

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1); // 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300); // 输出图片大小
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);

        Log.e(TAG,"cropUri = "+cropUri.toString());

        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, REQUEST_SMALL_IMAGE_CUTTING);
    }

    //上传图片文件的操作
    public void uploadImg() {
        StringBuilder urlParams = new StringBuilder();
        String url = HttpUrl.SaveXcpzImage;
        String uploadType = getIntent().getStringExtra("type");
        if(null != uploadType && "grxxUpload".equals(uploadType)){
            url = HttpUrl.SaveGrjbxxImage;
        }
        if (NetWorkUtils.isNetworkConnected(con)) {  //////网络存在
            RequestParams ps = new RequestParams();
            final String path = (String) SharedPreferencesUtils.getParam(this, Constants.UPLOAD_IMAGE, "");// 获取图片路径
            File file = new File(path);
            if (file.exists()) {
                Log.e(TAG,"have file");
                Bitmap bmp = BitmapFactory.decodeFile(path);
                ByteArrayOutputStream baos=new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
                final byte [] bitmapByte =baos.toByteArray();

                if (!StringUtils.isEmpty(path)) {
                    try {
                        //ps.put("img", new File(Environment.getExternalStorageDirectory() + "/" + picname + ".jpg"));
                        ps.put("file", new File(path),ContentType.IMAGE_JPEG.getMimeType());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }

                String cardnum = getIntent().getStringExtra("cardnum"),
                        tabId = getIntent().getStringExtra("tabId"),
                        tabType = getIntent().getStringExtra("tabType");
                urlParams.append("token=").append(SharedPreferencesUtils.getParam(con, "token", "").toString()).append("&");
                urlParams.append("cardnum=").append(cardnum).append("&");
                urlParams.append("tabId=").append(tabId).append("&");
                urlParams.append("tabType=").append(tabType).append("&");
                urlParams.append("type=").append("2");

                AsyncHttpClient client = new AsyncHttpClient();
                ps.setUseJsonStreamer(false);
                ps.setForceMultipartEntityContentType(true);
                client.setURLEncodingEnabled(false);

                client.post(this,UserClient.getUploadAbsoluteUrl2(url + "?" + urlParams.toString()), ps, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                        String content = new String(response);
                        Log.i("现场照片已保存", content);
                        RetMsg ret = JSON.parseObject(content, RetMsg.class);
                        if (ret.getCode().equals("200")) {
                            JSONObject j = JSON.parseObject(ret.getRd());
                            Intent intent = new Intent(CameraChoose.this, getIntent().getStringExtra("class").getClass());
                            intent.putExtra("img_record_id", j.getString("id"));
                            intent.putExtra("bitmap", bitmapByte);
                            setResult(119, intent);
                            finish();
                        } else {
                            SweetAlertDialogUtil.ErrorDialogNoFinish(con, "错误提示", ret.getInfo(), "确定");
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
                        System.out.println("statusCode: " + statusCode);
                        e.printStackTrace();
                        Log.i("个现场照片保存失败", new String(errorResponse));
                        MyToastUtil.ShowToast(con, "保存失败");
                    }
                });
            }else{
                Log.e(TAG,"no file");
                MyToastUtil.ShowToast(con, "个现场照片保存失败");
            }

        } else {  //网络不存在
            MyToastUtil.ShowToast(con, "保存失败");
        }
    }
}
